package com.jishaokang.filter;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.jishaokang.cache.ResultCache;
import com.jishaokang.dao.ForbidUserDAO;
import com.jishaokang.dao.UserDAO;
import com.jishaokang.model.dto.ForbidUser;
import com.jishaokang.model.dto.PowerClass;
import com.jishaokang.model.dto.User;
import com.jishaokang.util.ForbidUtil;
import com.jishaokang.util.MaskWordUtil;
import com.jishaokang.util.SpringUtil;
import com.jishaokang.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.lang.Integer.parseInt;

@WebFilter(urlPatterns = "/api/teacher/*",filterName = "TeacherFilter")
public class TeacherFilter implements Filter {

    @Autowired
    private ForbidUtil forbidUtil;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private MaskWordUtil maskWordUtil;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        if (forbidUtil == null) forbidUtil = (ForbidUtil) SpringUtil.getBean("forbidUtil");
        if (tokenUtil == null) tokenUtil = (TokenUtil) SpringUtil.getBean("tokenUtil");
        if (maskWordUtil == null) maskWordUtil = (MaskWordUtil) SpringUtil.getBean("maskWordUtil");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        BodyReaderHttpServletRequestWrapper myRequestWrapper;
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.addHeader("Content-Type" ,"application/json;charset=UTF-8");
        if (httpServletRequest.getRequestURL().indexOf("upload") == -1) {
        // 封装请求参数
        myRequestWrapper = new BodyReaderHttpServletRequestWrapper(httpServletRequest);

            System.out.println(111);

            // 假定session中有userId
            String body = myRequestWrapper.sessionStream;
            if (maskWordUtil.containMaskWord(body)) {
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(ResultCache.getDataError(100, "含有屏蔽词")));
                writer.flush();
                return;
            }
            System.out.println(body);
            String token = null;
            String regex = "\"token\": \"(.*?)\"";
            Matcher matcher = Pattern.compile(regex).matcher(body);
            while (matcher.find()) {
                token = matcher.group(1);
            }
            System.out.println(token);

            if (token == null) {

                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(ResultCache.getDataError(300, "教师未登录")));
                writer.flush();
                return;
            }
            //验证token
            Integer userId = tokenUtil.getUserIdByToken(token);
            if (userId == null) {

                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(ResultCache.getDataError(300, "教师未登录")));
                writer.flush();
                return;
            }
            PowerClass powerClass = null;
            try {
                powerClass = forbidUtil.refreshUserPower(userId);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println(powerClass);
            if (powerClass.getAllTeacher().contains("forbid")) {

                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(ResultCache.getDataError(401, "您已被封禁讲师权限,剩余时间：" +
                        parseInt(powerClass.getAllTeacher().substring(powerClass.getAllTeacher().indexOf("_")+1)) + "小时")));
                writer.flush();
                return;
            }

            if (powerClass.getTeacherAddCourse().contains("forbid") &&
                    (myRequestWrapper.getServletPath().contains("addCourse") || myRequestWrapper.getServletPath().contains("addChapter"))) {

                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(ResultCache.getDataError(402, "您已被禁止发布课程,剩余时间：" +
                        parseInt(powerClass.getTeacherAddCourse().substring(powerClass.getTeacherAddCourse().indexOf("_")+1)) + "小时")));
                writer.flush();
                return;
            }

            if (powerClass.getTeacherAddLive().contains("forbid") && myRequestWrapper.getServletPath().contains("addLive")) {

                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(ResultCache.getDataError(403, "您已被禁止发布直播,剩余时间：" +
                        parseInt(powerClass.getTeacherAddLive().substring(powerClass.getTeacherAddLive().indexOf("_")+1)) + "小时")));
                writer.flush();
                return;
            }
            filterChain.doFilter(myRequestWrapper, servletResponse);
        }
        else{
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
    }


}